package com.sun.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UploadFile {

    @RequestMapping("/uploadFile")
    public String upload(
            @RequestParam(value = "username",required=false) String username,
            @RequestParam(value = "headImg") MultipartFile file,
            Model model,
            HttpServletRequest request){
        System.out.println("表单名"+file.getName());
        System.out.println("文件名"+file.getOriginalFilename());
        try {

            file.transferTo(new File(request.getServletContext().getRealPath("WEB-INF/file/") + file.getOriginalFilename()));
            model.addAttribute("msg","文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("msg","文件上传失败");
        }
        //文件保存
        return "success";
    }

    @RequestMapping("/multiUploadFile")
    public String uploadFiles(
            @RequestParam(value = "username",required = false) String user,
            @RequestParam("headImg") MultipartFile[] files,
            Model model,
            HttpServletRequest request
    ){
        for(MultipartFile file:files){
            if(!file.isEmpty()){
                System.out.println("表单名"+file.getName());
                System.out.println("文件名"+file.getOriginalFilename());
                try {
                    file.transferTo(new File(request.getServletContext().getRealPath("WEB-INF/file/")+file.getOriginalFilename()));
                    model.addAttribute("msg","文件上传成功");
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("msg","文件上传失败");
                }
            }

        }

        return "success";
    }
}
